from django.contrib.auth import authenticate, login
# from django.contrib.auth.views import login
from accounts.validators import Checkpasswd
from .fields import PasswordField, UsernameField
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from .models import *


class UserRegisterForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ('username',  'email', 'department', 'mobile', "user_key")

    def clean_email(self):
        email = self.cleaned_data.get('email')
        is_exist = CustomUser.objects.filter(email=email)
        if is_exist.exists():
            raise forms.ValidationError(f"{email}用户已存在")
        return email


class LoginForm(forms.Form):
    """登录表单"""
    username = UsernameField(required=True, max_length=12, min_length=4)
    password = PasswordField(required=True, max_length=12, min_length=6)

    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        self.user_cache = None
        super(LoginForm, self).__init__(*args, **kwargs)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            print(self.user_cache)

            if self.user_cache is None:
                raise forms.ValidationError("您输入的用户名或密码不正确!")
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError("您输入的用户名或密码不正确!")
            else:
                login(self.request, self.user_cache)
        return self.cleaned_data


class CustomUserCreationForm(UserCreationForm):
    """
    创建用户表单
    A form that creates a user, with no privileges, from the given email and
    password.
    """

    class Meta:
        model = CustomUser
        fields = '__all__'


class CustomUserChangeForm(UserChangeForm):
    """
    修改用户表单
    A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """

    class Meta:
        model = CustomUser
        fields = '__all__'


class CurrentCustomUserForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ('email',
            
                  'mobile')


class UserInitPasswordForm(forms.ModelForm):
    """ 用户初始化密码表单 """
    newpassword = PasswordField(required=True, max_length=128, min_length=6, label='新密码', widget=forms.PasswordInput, )
    renewpassword = PasswordField(required=True, max_length=128, min_length=6, label='确认密码',
                                  widget=forms.PasswordInput, )
    pk = forms.CharField(required=False, label="pk")

    class Meta:
        model = CustomUser
        fields = ['newpassword', 'renewpassword', 'pk']

    def clean(self):
        data = self.cleaned_data
        newpassword = data.get("newpassword")
        renewpassword = data.get("renewpassword")

        if newpassword != renewpassword or not newpassword:
            """ 密码不一致 或者密码为空 """
            raise forms.ValidationError("两次输入的密码不一致")

        check_passwd = Checkpasswd(newpassword)
        if not check_passwd:
            raise forms.ValidationError("密码不符合规则:密码必须为英文数字特殊符号组成")

        return super().clean()

    def save(self, commit=True):
        user = super().save(commit=False)
        newpassword = self.cleaned_data.get("newpassword")
        user.set_password(newpassword)
        user.is_staff = 1
        user.is_active = 1
        if commit:
            user.save()

        return user


class ChangePasswordForm(forms.Form):
    """
        修改密码表单
    """
    newpassword = PasswordField(max_length=18, min_length=6, label="新密码", widget=forms.PasswordInput, )
    renewpassword = PasswordField(max_length=18, min_length=6, label="确认新密码", widget=forms.PasswordInput, )

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super().__init__(*args, **kwargs)

    def clean(self):
        newpassword = self.cleaned_data.get('newpassword')
        renewpassword = self.cleaned_data.get('renewpassword')
        if newpassword and renewpassword:
            if newpassword != renewpassword:
                raise forms.ValidationError("此处必须输入和上栏密码相同的内容")
        return renewpassword

    def save(self, commit=True):
        """
        Saves the new password.
        """
        # print self.user.set_password(self.cleaned_data["newpassword"])
        if commit:
            self.user.save()
        return self.user


class ResetPasswordForm(forms.ModelForm):
    """ 重置密码 """

    class Meta:
        model = CustomUser
        fields = ['email']


class ResetPasswordDoneForm(forms.ModelForm):
    """ 重置密码确认"""
    newpassword = PasswordField(required=True, max_length=128, min_length=6, label='新密码:', widget=forms.PasswordInput, )
    renewpassword = PasswordField(required=True, max_length=128, min_length=6, label='确认密码:',
                                  widget=forms.PasswordInput, validators=[Checkpasswd])

    class Meta:
        model = CustomUser
        fields = ['newpassword', 'renewpassword', ]

    def clean_newpassword(self):
        newpassword = self.cleaned_data.get("newpassword")
        renewpassword = self.cleaned_data.get("renewpassword")

        if newpassword != renewpassword:
            raise forms.ValidationError("两次密码不一致")
        return newpassword


class DepartmentFrom(forms.ModelForm):
    """ 部门表单"""

    class Meta:
        model = Department_Mode
        fields = "__all__"
